﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Deepseek_Robot.Modules.Models;
using System;
using System.IO;
using System.Windows.Controls;

namespace Deepseek_Robot.Modules.ViewModels
{
    public partial class ChartViewModel : ObservableObject
    {
        private string _videoSource;
        public string VideoSource
        {
            get => GetLatestVideoPath();
            set
            {
                if (SetProperty(ref _videoSource, value))
                {
                    _isVideoSourceSet = true;
                    if (_mediaElement != null)
                    {
                        _mediaElement.Play();
                    }
                }
            }
        }

        private MediaElement _mediaElement;
        private bool _isVideoSourceSet = false;

        public ChartViewModel()
        {
            // 注册消息接收
            WeakReferenceMessenger.Default.Register<VideoPathMessage>(this, (r, m) =>
            {
                VideoSource = m.VideoPath;
                PlayVideo();
            });
        }

        [RelayCommand]
        private void PlayVideo()
        {
            if (_mediaElement != null && !string.IsNullOrEmpty(VideoSource))
            {
                _mediaElement.Source = new Uri(VideoSource, UriKind.RelativeOrAbsolute);
                _mediaElement.Play();
                if (System.IO.File.Exists(VideoSource))
                {
                    Console.WriteLine("视频文件存在");
                }
                else
                {
                    Console.WriteLine("视频文件不存在");
                }
            }
        }

        [RelayCommand]
        public void SetMediaElement(MediaElement mediaElement)
        {
            _mediaElement = mediaElement;
            if (_isVideoSourceSet && !string.IsNullOrEmpty(VideoSource))
            {
                _mediaElement.Source = new Uri(VideoSource, UriKind.RelativeOrAbsolute);
            }
        }

        [RelayCommand]
        private void PauseVideo()
        {
            _mediaElement?.Pause();
        }
        [RelayCommand]
        private void StopVideo()
        {
            _mediaElement?.Stop();
        }

        private string GetLatestVideoPath()
        {
            string directoryPath =@"C:\Users\DC\Videos\";
            DirectoryInfo directory = new DirectoryInfo(directoryPath);
            FileInfo[] videoFiles = directory.GetFiles("*.mp4"); // 假设视频文件为 MP4 格式
            if (videoFiles.Length > 0)
            {
                Array.Sort(videoFiles, (f1, f2) => f2.LastWriteTime.CompareTo(f1.LastWriteTime));
                return videoFiles[0].FullName;
            }
            return null;
        }
    }
}